using Cooking.Client.CaliburnExtensions;
using Cooking.Client.Services;
using System.Linq;

namespace Cooking.Client.ViewModels.Coroutines
{
    public class EnsureRecipeTitleUniquenessCoroutine : SimpleCoroutine
    {
        private readonly string recipeTitle;
        private object requestHandle;

        public EnsureRecipeTitleUniquenessCoroutine(string recipeTitle)
        {
            this.recipeTitle = recipeTitle;
        }

        public bool IsUnique { get; set; }
        public IQueryAgent QueryAgent { get; set; }

        protected override void OnExecute()
        {
            string queryString = string.Format("IsUnique?recipeTitle='{0}'", recipeTitle);

            requestHandle = QueryAgent.ExecuteQuery<bool>(queryString, results =>
            {
                requestHandle = null;

                IsUnique = results.Single();

                OnComplete();
            });
        }

        public void Cancel()
        {
            if (requestHandle != null)
            {
                QueryAgent.CancelQuery(requestHandle);
            }
        }
    }
}